<?php
	require_once(dirname(__FILE__)."/session_auth.php");
        // we don't have to update $_SESSION
        session_write_close();
?>
<?php
	require_once(dirname(__FILE__)."/config.php");
	require_once(dirname(__FILE__)."/../inc/class/server/ServerDao.php");
	require_once(dirname(__FILE__)."/response.php");
?>
<?php
/*
 * Proxy Enable
 * Created: 200904 (TT Tsai)
 */
        // load data from POST string
        $widgetRequest = json_decode($HTTP_RAW_POST_DATA,true);
        if( $widgetRequest == null ) {
                // input format error
                make_error_response( PENABLE_ERRCODE_INVALIDFORMAT, PENABLE_ERRCODE_INVALIDFORMAT_MSG);
                exit;
        }

	// check enable
	if( !isset($widgetRequest["enable"]) ) {
		make_error_response( PENABLE_ERRCODE_LACKINPUT, PENABLE_ERRCODE_LACKINPUT_MSG);
		exit;
	}
	$proxyenable = $widgetRequest["enable"];
	if( ($proxyenable != 0) && ($proxyenable != 1) ) {
		make_error_response( PENABLE_ERRCODE_LACKINPUT, PENABLE_ERRCODE_LACKINPUT_MSG);
		exit;
	}

	// check proxyid
	if( $proxyenable == 1 ) {
		if( !isset($widgetRequest['proxyid']) ) {
			make_error_response( PENABLE_ERRCODE_LACKINPUT, PENABLE_ERRCODE_LACKINPUT_MSG);
			exit;
		}
		$proxyid = $widgetRequest["proxyid"];
	}

	// userid
	if( !isset($_SESSION['uid']) ) {
		make_error_response( PENABLE_ERRCODE_WFERR, PENABLE_ERRCODE_WFERR_MSG.": retrieving userid failed");
		exit;
	}
	$userid = $_SESSION['uid'];

	// create ServerList object
	$slistobj = new WFServerDao( $wfconf_dbconfig, $userid);
	if( $slistobj->isFailed() ) {
		make_error_response( PENABLE_ERRCODE_DBINIT, PENABLE_ERRCODE_DBINIT_MSG.": ".$slistobj->getErrMessage());
		exit;
	}

	// getall
	$slist = $slistobj->getall();

	foreach( $slist as $rec ) {
		if( $rec["id"] != 1 ) {
			// update proxy_enable
			$rec["hostinfo"]["proxy_enable"] = $proxyenable;
			if( $proxyenable == 1 ) {
				$rec["hostinfo"]["proxy_id"] = $proxyid;
			}
			// do real update
			//$slistobj->update( $rec["id"], $name, json_encode($hinfo));
			$slistobj->update( $rec["id"], $rec["name"], $rec["hostinfo"]);
			if( $slistobj->isFailed() ) {
				make_error_response( PENABLE_ERRCODE_DBERR, PENABLE_ERRCODE_DBERR_MSG.": ".$slistobj->getErrMessage());
				exit;
			}
		}
	}
	if( $proxyenable == 1 ) {
		make_successful_response( 0, PENABLE_OK_ENABLE_MSG);
	} else {
		make_successful_response( 0, PENABLE_OK_DISABLE_MSG);
	}
?>
